//
//  MoreViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/24.
//

import UIKit
import SVProgressHUD
import StoreKit

class MoreViewController: UIViewController {
    
    var webTitle: String?
    var webURL: String?
    
    let funtionArray: [String] = ["解压小视频", "解压音乐", "备份", "建议反馈", "好评鼓励", "关于我们"]

    @IBOutlet weak var tableView: UITableView!
    //MoreTableViewCell
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webTitle = UserDefaults.standard.string(forKey: "webTitle")
        webURL = UserDefaults.standard.string(forKey: "webURL")

        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "MoreTableViewCell", bundle: .main), forCellReuseIdentifier: "MoreTableViewCell")
        tableView.tableFooterView = createFooterView()
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        tableView.separatorColor = UIColor.hexColor(hex: "#E8E8E8")
        
        if UserDefaults.standard.object(forKey: "isFirst") == nil
        {
            UserDefaults.standard.setValue(1, forKey: "isFirst")
            UserDefaults.standard.setValue(1, forKey: "music")
            UserDefaults.standard.synchronize()
        }
    }
    
    func createFooterView() -> UIView {
        
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: screen_width, height: 350.0))
        let lineView = UIView(frame: CGRect(x: 0, y: 0, width: screen_width, height: 0.5))
        lineView.backgroundColor = UIColor.hexColor(hex: "#E8E8E8")
        footerView.addSubview(lineView)
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 30.0, left: 25.0, bottom: 0, right: 25.0)
        let collectionView = UICollectionView(frame: footerView.bounds, collectionViewLayout: flowLayout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "MoreCollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "MoreCollectionViewCell")
        footerView.addSubview(collectionView)
        return footerView
    }
    
    // 友盟页面统计
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        MobClick.beginLogPageView("更多")
        MobClick.event("pages_num", attributes: ["GengDuo":"进入更多"])
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("更多")
        MobClick.event("pages_num", attributes: ["GengDuo":"离开更多"])
    }

}

extension MoreViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 55.0 }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: MoreTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MoreTableViewCell") as! MoreTableViewCell
        cell.delegate = self
        cell.currentIndex = indexPath.row
        
        if indexPath.row == 0
        {
            cell.label0.text = "PIN密码锁"
            cell.label1.isHidden = true
            cell.imgV.image = UIImage(named: "密码锁")
            cell.statusSwitch.isHidden = false
            cell.arrowImageView.isHidden = true
            
            guard let _ = UserDefaults.standard.object(forKey: "codeString") as? String else {
                cell.statusSwitch.isOn = false
                return cell
            }
            cell.statusSwitch.isOn = true
            
        }
        else if indexPath.row == 1
        {
            cell.label0.text = "通知"
            
            cell.imgV.image = UIImage(named: "通知")
            cell.statusSwitch.isHidden = false
            cell.arrowImageView.isHidden = true
            
            guard let alertTime = UserDefaults.standard.object(forKey: "UserDailyAlert") as? String else {
                cell.label1.isHidden = true
                cell.label1.text = ""
                cell.statusSwitch.isOn = false
                return cell
            }
            cell.label1.isHidden = false
            cell.label1.text = "每天 " + alertTime
            cell.statusSwitch.isOn = true
        }
        else if indexPath.row == 2
        {
            
            cell.label0.text = "心情编辑"
            
            cell.imgV.image = UIImage(named: "心情编辑")
            cell.statusSwitch.isHidden = true
            cell.arrowImageView.isHidden = false
            
            
            cell.label1.isHidden = true
            
        }
        else if indexPath.row == 3
        {
            
            cell.label0.text = "活动编辑"
            
            cell.imgV.image = UIImage(named: "活动编辑")
            cell.statusSwitch.isHidden = true
            cell.arrowImageView.isHidden = false
            
            
            cell.label1.isHidden = true
            
        }
        else if indexPath.row == 4
        {
            cell.label0.text = "订阅完整版"
            cell.label1.isHidden = false
            cell.imgV.image = UIImage(named: "订阅完整版")
            cell.arrowImageView.isHidden = false
            cell.label1.text = "试用7天后仅支持简单记录"
            cell.label1.textColor = UIColor.hexColor(hex: "#888888")
            cell.label1.font = UIFont(name: "PingFang SC", size: 12)
            cell.conLable1.constant = -15
            cell.statusSwitch.isHidden = true
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        
        if indexPath.row == 2
        {
            let viewController = FeelingEditVCViewController()
            viewController.title = "心情编辑"
            navigationController?.pushViewController(viewController, animated: true)
            
        }else if indexPath.row == 3{
            
            let viewController = ActiveEditVCViewController()
            viewController.title = "活动编辑"
            navigationController?.pushViewController(viewController, animated: true)
            
        }else if indexPath.row == 4{
            
            let vc = PayViewController()
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true, completion: nil)
            
//            let viewController = WebUrlViewController()
//            viewController.webUrlType = WebUrlTypePromotion
//            viewController.webTitle = webTitle!
//            viewController.webURL = webURL!
//
//            navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
}

extension MoreViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 6 }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let marginX = 25.0
        let itemLength = (Double(collectionView.width) - marginX * 4.0) / 3.0 - 1.0
        
        return CGSize(width: itemLength, height: itemLength + 30.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 25.0 }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 30.0 }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: MoreCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MoreCollectionViewCell", for: indexPath) as! MoreCollectionViewCell
        cell.label.text = funtionArray[indexPath.row]
        cell.imgV.image = UIImage(named: funtionArray[indexPath.row])
        cell.newImage.image = UIImage(named: "NEW")
        if indexPath.row == 1
        {
            if UserDefaults.standard.object(forKey: "music") as? Int == 1
            {
                cell.newImage.isHidden = false
            }else{
                cell.newImage.isHidden = true
            }
        }else{
            cell.newImage.isHidden = true
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath)
        //["解压小视频", "导出PDF", "备份", "建议反馈", "好评鼓励", "关于我们"]
        
        switch indexPath.row {
        case 0:
            let viewController = WebUrlViewController()
            viewController.webUrlType = WebUrlTypeVideo
            navigationController?.pushViewController(viewController, animated: true)
        case 1:
            let viewController = MusicViewController()
            UserDefaults.standard.setValue(2, forKey: "music")
            UserDefaults.standard.synchronize()
            viewController.title = "解压音乐"
            navigationController?.pushViewController(viewController, animated: true)
        case 2:
//            SVProgressHUD.showInfo(withStatus: "敬请期待")
//            SVProgressHUD.dismiss(withDelay: 2.0)
            
            showiCloudAlert()
        case 3:
            let viewController = WebUrlViewController()
            viewController.webUrlType = WebUrlTypeFeedback
            navigationController?.pushViewController(viewController, animated: true)
        case 4:
            self.showReviewAlert()
//            SVProgressHUD.showInfo(withStatus: "敬请期待")
//            SVProgressHUD.dismiss(withDelay: 2.0)
        case 5:
            let viewController = WebUrlViewController()
            viewController.webUrlType = WebUrlTypeAbout
            navigationController?.pushViewController(viewController, animated: true)
        default:
            break
        }
        
    }
    
    private func showiCloudAlert() {
        
        let alertVC = UIAlertController(title: "提示", message: "选择操作", preferredStyle: UIAlertController.Style.actionSheet)

        alertVC.addAction(UIAlertAction(title: "备份到iCloud", style: UIAlertAction.Style.default, handler: { action in

            SVProgressHUD.setDefaultMaskType(.black)
            SVProgressHUD.show()
            // 备份数据
            SyncCloudManager.shared.syncCloud { success, errMsg in

                if success {
                    SVProgressHUD.showSuccess(withStatus: "备份iCloud数据成功")
                } else {
                    SVProgressHUD.showError(withStatus: "备份iCloud数据失败: [\(errMsg)]")
                }
            }
        }))

        alertVC.addAction(UIAlertAction(title: "从iCloud恢复", style: UIAlertAction.Style.destructive, handler: { action in

            let alertVC1 = UIAlertController(title: "提示", message: "使用恢复时，会覆盖本地所有数据，请确保iCloud数据是最新的", preferredStyle: UIAlertController.Style.alert)
            alertVC1.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: { action in

            }))
            
            alertVC1.addAction(UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: { action in

                SVProgressHUD.setDefaultMaskType(.black)
                SVProgressHUD.show()

                // 拉云数据
                SyncCloudManager.shared.fetchCloud { success, errMsg in

                    if success {
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "createSucceed"), object: nil)
                        SVProgressHUD.showSuccess(withStatus: "同步iCloud数据成功")
                    } else {
                        SVProgressHUD.showError(withStatus: "同步iCloud数据失败: [\(errMsg)]")
                    }
                }
            }))
            self.present(alertVC1, animated: true, completion: nil)

        }))
        
        alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel, handler: { action in
        }))

        self.present(alertVC, animated: true, completion: nil)
    }
    
    func showReviewAlert(){
        
        SKStoreReviewController.requestReview()
    }
    
}

extension MoreViewController: MoreTableViewCellDelegate {
    
    func switchStatusIsOn(status: Bool, currentIndex: Int) {
        guard currentIndex >= 0 else { return }

        print("status === \(status), currentIndex === \(currentIndex)")
        
        guard currentIndex == 1 else {
            
            let codeString = UserDefaults.standard.object(forKey: "codeString") as? String
            if codeString != nil {
//                showCodeViewController(codeType: .close)
                UserDefaults.standard.removeObject(forKey: "codeString")
                UserDefaults.standard.synchronize()
            } else {
                showCodeView()
            }
            return
        }
        
        guard status == true else {
            UserDefaults.standard.removeObject(forKey: "UserDailyAlert")
            UserDefaults.standard.synchronize()
            
            let cell: MoreTableViewCell = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as! MoreTableViewCell
            cell.label1.text = ""
            cell.label1.isHidden = true
            
            UNUserNotificationCenter.current().removeAllDeliveredNotifications()
            
            // 友盟功能统计
            MobClick.event("function_num", attributes: ["TongZhi":"关闭通知"])
            
            return
        }
        
        let pickerView = UIPickerView(frame: CGRect(x: 35.0, y: 70.0, width: 200.0, height: 240.0))
        pickerView.delegate = self
        pickerView.dataSource = self
        
        let hour = NSString.currentHour()
        let hourInt: Int = Int(hour) ?? 0
        
        let minute = NSString.currentMinute()
        let minuteInt: Int = Int(minute) ?? 0
        
        pickerView.selectRow(hourInt, inComponent: 0, animated: false)
        pickerView.selectRow(minuteInt, inComponent: 1, animated: false)
        
        let alertC = UIAlertController(title: "提示", message: "请选择时间\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
        alertC.view.addSubview(pickerView)
        alertC.addAction(UIAlertAction(title: "确定", style: .default, handler: { [weak self] (_) in
            
            let selectIndex0 = pickerView.selectedRow(inComponent: 0)
            let selectIndex1 = pickerView.selectedRow(inComponent: 1)
            
            let string = String(format: "%02d:%02d", selectIndex0, selectIndex1)
            
            let cell: MoreTableViewCell = self?.tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as! MoreTableViewCell
            cell.label1.isHidden = false
            cell.label1.text = "每天 " + string
            
            UserDefaults.standard.setValue(string, forKey: "UserDailyAlert")
            UserDefaults.standard.synchronize()
            
            self?.registerLocalNotification()
            
            // 友盟功能统计
            MobClick.event("function_num", attributes: ["TongZhi":"开启通知"])
        }))
        alertC.addAction(UIAlertAction(title: "取消", style: .destructive, handler: { [weak self] (_) in
            let cell: MoreTableViewCell = self?.tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as! MoreTableViewCell
            cell.statusSwitch.setOn(false, animated: true)
            cell.label1.text = ""
            cell.label1.isHidden = true
        }))
        present(alertC, animated: true, completion: nil)
        
    }
    
}

extension MoreViewController {
    func registerLocalNotification() {
        
        let string: String = UserDefaults.standard.value(forKey: "UserDailyAlert") as! String

        let hour = (string as NSString).substring(to: 2)
        let minute = (string as NSString).substring(from: string.count - 2)
        
        let hourInt: Int = Int(hour) ?? 0
        let minuteInt: Int = Int(minute) ?? 0
        
        let content = UNMutableNotificationContent()
        content.title = "提示"
        content.subtitle = "您设定的每日提醒时间:\(string)已经到了"
        content.sound = UNNotificationSound.default
        
        var dateCom: DateComponents = DateComponents()
        dateCom.hour = hourInt
        dateCom.minute = minuteInt
        
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateCom, repeats: true)
        let request = UNNotificationRequest(identifier: "noticeId", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request) { (error) in
            print(error)
        }
        
    }
}

extension MoreViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 { return 24 }
        return 60
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { String(format: "%02d", row) }
}

extension MoreViewController: CodeViewDeleagate {
    
    func showCodeView(codeType: CodeVCType = .setting) {
       
        let codeView = CodeView(frame: CGRect(x: 0, y: 0, width: screen_width, height: screen_height))
        codeView.codeType = codeType
        codeView.delegate = self
        
        UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(codeView)
    }
    
    func codeViewUnlock() { // 解锁
        
    }
    
    func codeViewClose() { // 关闭
        
        let cell: MoreTableViewCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! MoreTableViewCell
        let codeString = UserDefaults.standard.object(forKey: "codeString") as? String
        if codeString != nil {
            cell.statusSwitch.isOn = true
        } else {
            cell.statusSwitch.isOn = false
        }
        
    }
    
}

